package handler

import (
    "encoding/json"
    "fcs-api/src/app/business"
    "fcs-api/src/app/model"
    "net/http"

    i18n "git.inspur.com/x/common/i18n"
    "github.com/emicklei/go-restful"
)

func (api *APIHandler) handleCallback(request *restful.Request, response *restful.Response) {
    logger.Debug("handleInvokeFunction start.")

    invokeInfo, err := validateFunctionCallback(request)
    if err != nil {
        _ = logger.Warn("validate callback error, %s", err)
        handleInternalError(response, err)
        return
    }
    invokeInfoStr, _ := json.Marshal(invokeInfo)
    logger.Debug("invoke info str is %s", string(invokeInfoStr))
    // 非阻塞处理
    go func() {
        api.InvokeChan <- invokeInfo
    }()
    logger.Debug("handleInvokeFunction end.")
    response.WriteHeader(http.StatusOK)
}

func (api *APIHandler) handleGetLog(request *restful.Request, response *restful.Response) {
    logger.Debug("handleGetLog start.")
    logQuery, err := validateGetLog(request)
    if err != nil {
        handleInternalError(response, err)
        return
    }
    result, err := business.GetLogList(logQuery)
    if err != nil {
        handleInternalError(response, model.InternalServerError(model.FunctionLogError, i18n.GetMessage(request.Request, "fcs.template.query")))
        return
    }
    logger.Debug("handleGetLog end.")
    _ = response.WriteHeaderAndEntity(http.StatusOK, result)
}

func (api *APIHandler) handleGetMetrics(request *restful.Request, response *restful.Response) {
    logger.Debug("handleGetMetrics start.")
    metricQuery, err := validateGetMetrics(request)
    if err != nil {
        handleInternalError(response, err)
        return
    }
    data, err := business.GetMetric(metricQuery)
    if err != nil {
        handleInternalError(response, model.InternalServerError(model.FunctionMetricsError, i18n.GetMessage(request.Request, "fcs.metric.monitor")))
        return
    }
    logger.Debug("handleGetMetrics end.")
    _ = response.WriteHeaderAndEntity(http.StatusOK, map[string]interface{}{
        "points": data,
    })
}

func (api *APIHandler) handleGetRegionMetrics(request *restful.Request, response *restful.Response) {
    logger.Debug("handleGetRegionMetrics start.")
    user := currentUser(request)
    result, err := business.GetRegionMetric(user)
    if err != nil {
        handleInternalError(response, err)
        return
    }
    _ = response.WriteHeaderAndEntity(http.StatusOK, result)
}

func (api *APIHandler) handleGetRegionMetricsFunction(request *restful.Request, response *restful.Response) {
    logger.Debug("handleGetRegionMetrics start.")
    user := currentUser(request)
    result, err := business.GetRegionMetricFunction(user)
    if err != nil {
        handleInternalError(response, err)
        return
    }
    _ = response.WriteHeaderAndEntity(http.StatusOK, result)
}
